//
//  JAMainController.swift
//  JAWeiBo
//
//  Created by Arvin on 17/4/2.
//  Copyright © 2017年 Arvin. All rights reserved.

/*
 extension的用法:
 1. 扩展类的功能: 比如便利构造器
 2. 实现代理
 3. 给代码分组, 让代码变得更易读
 */

import UIKit

class JAMainController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置UI
        setupUI()
    }
}
    
 //MARK: - "发布微博"按钮点击事件
extension JAMainController {
        /// 在swift中, 一旦事件使用了fileprivate或者private修饰, 就必须添加一个 @objc修饰符
        @objc fileprivate func compose(button: UIButton) {
            
            
            if JAUserAccount.shared.isLogin {
                let compose = JAComposeController()
                let nav = UINavigationController(rootViewController: compose)
                present(nav, animated: true, completion: nil)
            } else {
                let login = JALoginController()
                let nav = UINavigationController(rootViewController: login)
                present(nav, animated: true, completion: nil)
            }
    }
}

//MARK: - 设置UI
extension JAMainController {
        
   fileprivate func setupUI() {
        
        self.view.backgroundColor = UIColor.white
        //添加所有的子控制器
        addChildControllers()
        
        //添加"发布"按钮
        setCompseButton()
    
       //设置tabbar的阴影线条
        setupShadowImage()
    
       //设置欢迎页和新特性页
       setWelcomeOrNewFeatureView()

}
    //设置欢迎页和新特性页
    func setWelcomeOrNewFeatureView() {
        //判断是否有新特性
       let isNewFeature = Bundle.main.isNewFeature
        
        if(JAUserAccount.shared.isLogin == true) {
            //判断是否有新特性
            if isNewFeature == true {
                //展示新特性页
                let newFeature = JANewFeaureView()
                
                self.view .addSubview(newFeature)
                
            }else {
                //展示欢迎页面
                let welcome = JAWelcomeView()
//                welcome.backgroundColor = UIColor.orange
                self.view .addSubview(welcome)

                
            }
        }
    }
    
    ///设置tabbar的阴影线条
    func setupShadowImage() {
        tabBar.backgroundImage = UIImage(named:"tabbar_background")
        tabBar.shadowImage = UIImage.pureImage(color: UIColor(white: 0.9, alpha: 0.9))
    }
    ///tabbar底部的发布按钮
    func setCompseButton() {
        
//        //设置"发布"按钮图片
//        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
//        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
//        
//        //设置"发布"按钮背景图片
//        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
//        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
//        
//        //添加点击事件
//        button.addTarget(self, action: #selector(compose(button:)), for: .touchUpInside)
        
        //添加发布按钮
        let button = UIButton(title: nil, image: "tabbar_compose_icon_add", bgImage: "tabbar_compose_button", target: self, action: #selector(compose(button:)))
        
        //设置frame
        let width = tabBar.frame.width/5
        button.frame = tabBar.bounds.insetBy(dx: width*2-2, dy: 6)
        
        //将按钮添加到tabbar上
        tabBar.addSubview(button)
    }

    ///添加所有的子控制器
    func addChildControllers() {
        //获取url
        if let url = Bundle.main.url(forResource: "main.json", withExtension: nil),
        
            //使用url,获取data
            let jsonData = try? Data(contentsOf: url),
        
            //使用data对jsonData做反例化操作,返回的是一个可选的Any类型
        let object = try? JSONSerialization
        .jsonObject(with: jsonData, options: []),
        
            //将Any类型转成字典数组
            let dictArry = object as? [[String: Any]] {
            
            //创建空数组
            var controllers: [UINavigationController] = []
            
            //遍历参数字典
            for dic in dictArry {
                
                //创建子控制器
                let nav = generateChildController(dict: dic)
                controllers.append(nav!)
            }
            
            //设置所有的子控制器
            self.viewControllers = controllers
            
        }
        
        
    
    }
    
    //添加单个控制器
    func generateChildController(dict: [String: Any]) -> UINavigationController? {
        
        //1.通过字符串,创建类,并使用类来创建控制器
        if let clsName = dict["clsName"] {
            
             //类名在swift中, 必须加一个项目名的前缀
            let className = "JAWeiBo" + "." + "\(clsName as! String)"
            //使用字符串来创建类,必须转成Type类型
            if let cls = NSClassFromString(className) as? JARootController.Type {
            
            //使用类,创建一个子控制器对象
            let controller = cls.init()
                
            //给控制器设置title
                let title = dict["title"] as? String
                controller.title = title
                controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.gray], for: .normal)
                controller.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: .selected)
                
                //给子控制器的tabbarItem设置图片
                if let imageName = dict["imageName"] {
                    let image = UIImage(named: "tabbar_\(imageName)")?.withRenderingMode(.alwaysOriginal)
                    
                    let selectedImage = UIImage(named: "tabbar_\(imageName)_selected")?.withRenderingMode(.alwaysOriginal)
                    
                    controller.tabBarItem.image = image
                    controller.tabBarItem.selectedImage = selectedImage
                    
                }
                
                //访客视图的文本和图标信息赋值给controller
                controller.visitorDic = dict["visitorInfo"] as? [String: Any]
                
                //使用子控制器创建UINavigationController
                let nav = UINavigationController(rootViewController: controller)

                return nav
            }
        }
     
        
        return nil
        
    }
}
